import React, { useState, useEffect } from 'react';
import {
  FileExcelOutlined, SearchOutlined, ReloadOutlined,
  PlusSquareOutlined, EditOutlined, SwapOutlined,
  CloudUploadOutlined
} from '@ant-design/icons';
import { Select, Button, Spin, Tabs, Modal } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';

import {
  openNotification_util, fetchsync_util, useexcelauto,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS,
  addkey_for_mxdata
} from '../util/util.js'
var storage = window.localStorage;
const { Option } = Select;
import Sortable from '../newmes/sortable.js';
import { use_gys_initcolmun, use_gys_initcolmun_import } from '../gyszx/use_gyszx_config.js';
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';
import ResizableTable from '../newmes/Resize_table_hook.js';
import XLSX from 'xlsx';

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});

const Gys_list = () => {
  const history = useHistory();
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [isloading, setisloading] = useState(false)
  const [importloading, setimportloading] = useState(false)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [ifshow, setifshow] = useState(true)
  const [listdata, setlistdata] = useState([])
  const [kb_listdata, setkb_listdata] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [columnarr, setcolumnarr] = useState(use_gys_initcolmun)
  const { setnowroute, collapsed } = useStore();
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [excelData, setExcelData] = useState(null);
  const [errorRows, setErrorRows] = useState([]);
  const [importError, setImportError] = useState([]);


  useEffect(() => {
    querylist()
    storage[`Pc_gys_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_gys_list_${storage.userid}`])) : setcolumnarr(columnarr)
    storage[`Pc_gys_list__initsize_${storage.userid}`] ? setinitSize(storage[`Pc_gys_list__initsize_${storage.userid}`]) : setinitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])

  const querylist = async () => {
    setisloading(true)
    storage[`Pc_gys_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_gys_list_${storage.userid}`])) : setcolumnarr(columnarr)
    let rtdata = await fetchsync_util("/admin/gyszx/gyslb", 'POST', {}, "json")
    // openNotification_util(rtdata.rtmessage)

    rtdata.resultdata.rtdata.forEach(element => {
      element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)

    });
    if (storage.yhlx == "租户用户") {
      rtdata.resultdata.rtdata = rtdata.resultdata.rtdata.filter(item => item.gysmc == storage.ygxm)
    }
    console.log(rtdata.resultdata.rtdata[0]?.gyswhzt, "111111111");
    setlistdata(dealnullorundenfined(rtdata.resultdata.rtdata.map((item)=>{
        item.gsdz = item.gsdz && item.gsdz !== "undefined" ? item.gsdz : ""
        item.fkfs = item.fkfs && item.fkfs !== "undefined" ? item.fkfs : ""
        item.dj = item.dj && item.dj !== "undefined" ? item.dj : ""
        item.sj = item.sj && item.sj !== "undefined" ? item.sj : ""
        item.ghcp = item.ghcp ? item.ghcp : ""
        item.lxr = item.lxr ? item.lxr : ""
        item.hzzt = item.hzzt ? item.hzzt : ""
        item.erpdm = item.erpdm ? item.erpdm : ""
        item.gysdm = item.gysdm ? item.gysdm : ""
        item.bzsm = item.bzsm ? item.bzsm : ""
        return item
    })))
    setselectedRowKeys([])
    setselectedRows([])
    setifshow(false)
    setisloading(false)
  }

  /**
   * 手动查询
   */
  const handleQuery = async () => {
    querylist()
  }
  /**
   * 新增
   */
  const handleadd = async () => {
    storage.pre_gys_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey('gys_form')
    setnowroute({ ...{ route: "/shipSRM/gyszx/gys_form", title: "供应商档案_新增" } })
  }
  /**
   * 编辑
   */
  const handleEdit = async (data, type) => {
    storage.pre_gys_item = JSON.stringify({ data, type })
    dropByCacheKey('gys_form')
    setnowroute({ ...{ route: "/shipSRM/gyszx/gys_form", title: "供应商档案_" + `${type == "edit" ? "编辑" : "查看"}` } })

  }
  /**
   * 删除
   */
  const handledelete = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("只可选择一条数据删除!")
    }
    else {
      let rtdata = await fetchsync_util("/admin/gyszx/delete_gys", 'POST', { selectedRows }, "json")
      rtdata.rtstatus ? querylist() : 1
    }
  }
  /**
   * 导出
   */
  const handleExport = async () => {
    let filtercol = JSON.parse(JSON.stringify(columnarr)).filter(item => item.show == true)
    filtercol.forEach(element => {
      element.width = element.width ? element.width / 7 : 10
    });
    // console.log("当前一共选中了多少行记录：",selectedRows.length)
    console.log("=============listdata=================", selectedRows.length == 0 ? listdata : selectedRows)
    useexcelauto(selectedRows.length == 0 ? listdata : selectedRows, filtercol, '供应商档案')
  }

  /**
  * 导入
  */
  const handleImport = async () => {
    let filtercol = JSON.parse(JSON.stringify(columnarr)).filter(item => item.show == true)
    filtercol.forEach(element => {
      element.width = element.width ? element.width / 7 : 10
    });
    // console.log("当前一共选中了多少行记录：",selectedRows.length)
    console.log("=============listdata=================", selectedRows.length == 0 ? listdata : selectedRows)
    useexcelauto(selectedRows.length == 0 ? listdata : selectedRows, filtercol, '供应商档案')
  }

  /**
   * 导出标准模板
   */
  const handlegetmb = async () => {
    var filtercol = use_gys_initcolmun_import()
    filtercol.forEach(element => {
      element.width = element.width ? element.width / 7 : 10
    });
    useexcelauto(kb_listdata, filtercol, '供应商档案导入模板')
  }

  const handleescelimport = async (data) => {
    setimportloading(true)
    let rtdata = await fetchsync_util("/admin/gyszx/gys_import", 'POST', data, "json")
    if (rtdata.resultdata.errorRows.length > 0) {
      setImportError(rtdata.resultdata.errorRows)
      setErrorRows([]);
    }
    else {
      setImportModalVisible(false);
      setImportError([]);
      setErrorRows([]);
      setExcelData(null);
      querylist()
    }
    openNotification_util("导入成功")
    setimportloading(false)
  }

  const onImportExcel = (file) => {
    const { files } = file.target;
    const fileReader = new FileReader();
    fileReader.onload = event => {
      try {
        const { result } = event.target;
        const workbook = XLSX.read(result, { type: 'binary' });
        let data = []; // 存储获取到的数据
        let errorRows = []; // 存储手机号格式错误的行

        // 手机号码校验正则或者是座机号码
        // const phoneRegex = /^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/;

        for (const sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            const sheetData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);

            // 校验每一行数据
            sheetData.forEach((row, index) => {
              // 检查手机号格式
              // if (!phoneRegex.test(row['手机'])) {
              //   errorRows.push({
              //     rowNumber: index + 2, // Excel从1开始,标题占1行,所以加2
              //     phone: row['手机']
              //   });
              // }

              // 处理日期格式
              // if (row['成立日期'] && typeof row['成立日期'] === 'number') {
              //   const date = new Date((row['成立日期'] - 25569) * 86400 * 1000);
              //   row['成立日期'] = date.toISOString().split('T')[0];
              // }
            });

            data = data.concat(sheetData);
          }
        }

        // 如果存在格式错误的行,提示用户
        if (errorRows.length > 0) {
          setErrorRows(errorRows)
          return;
        }

        var datastr = JSON.stringify(data);

        datastr = datastr.replace(/供应商名称/g, "gysmc").replace(/ERP代码/g, "erpdm").replace(/供货产品/g, "ghcp").
          replace(/联系人/g, "lxr").replace(/手机/g, "sj").replace(/公司地址/g, "gsdz").
          replace(/付款方式/g, "fkfs").replace(/等级/g, "dj");

        setExcelData(JSON.parse(datastr));
        console.log("=============datastr=================", datastr);
      } catch (e) {
        console.log('文件类型不正确');
        openNotification_util('文件类型不正确');
        return;
      }
    };
    // 以二进制方式打开文件
    fileReader.readAsArrayBuffer(files[0]);
  }


  const TabPaneItem = (title, listdata, columnarr, key) => {
    return <Tabs.TabPane tab={<span>{title} <span style={{
      display: 'inline-block', padding: '0 6px', fontSize: '12px', lineHeight: '14px', backgroundColor: '#a91f24',
      color: 'white', borderRadius: '8px', marginLeft: '4px'
    }}>{listdata.length}</span></span>}
      key={key}>
      {isloading ?
        (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
          <Spin /></div>)
        :
        (<ResizableTable tabledata={listdata} tablecolnum={columnarr}
          width={collapsed ? "94%" : "84%"}
          storageName={`Pc_gys_list_${storage.userid}`}
          sfdoubleclick="false" ifhiddencchangeselecttype="true"
          selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
          showCz={{ showEdit: true, showView: true }}
          handleEdit={(data) => handleEdit(data, "edit")}
          handleView={(data) => handleEdit(data, "view")}
          handleDelete={(data, type) => handledelete(data, type)}
          defaultPageSize={10}
          bordered
          handleselectson={(selectedRows, selectedRowKeys) => {
            setselectedRows(selectedRows)
            setselectedRowKeys(selectedRowKeys)
          }}
        />)
      }
    </Tabs.TabPane>
  }


  return (
    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem",paddingRight:"1%"
    }}>



      <div style={styles.kshcontainer}>
        <div style={{
          width: "99vw", height: "", backgroundColor: "white", overflowX: "scroll", margin: "0.5vw",
          paddingLeft: "1vw",paddingRight:"1vw"
        }}>
          {storage.yhlx == "管理用户" && <div style={styleobj.linestyleflex}>
            <span style={{ fontSize: "0.8rem", fontWeight: "500", color: "#666666" }}>工具栏</span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}>
              <ReloadOutlined />刷新</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleadd}>
              <PlusSquareOutlined />新 增</Button>
            {/* &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleEdit}>
              <EditOutlined /> 编 辑 </Button> */}
            {/* &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handledelete}>
              <MinusSquareOutlined /> 删 除</Button> */}
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleExport}>
              <FileExcelOutlined />导 出</Button>
            &nbsp;&nbsp;&nbsp;
            <Button style={{ backgroundColor: "#a91f24", color: "white", fontWeight: "800" }}
              onClick={() => setImportModalVisible(true)}>
              <CloudUploadOutlined /> 批量导入
            </Button>
            <Modal
              title="选择导入文件"
              visible={importModalVisible}
              onOk={() => {
                if (excelData && excelData.length > 0) {
                  handleescelimport(excelData);
                } else {
                  openNotification_util("请先选择并解析Excel文件");
                  setImportError([]);
                  setErrorRows([]);
                }
              }}
              onCancel={() => {
                setImportModalVisible(false);
                setImportError([]);
                setErrorRows([]);
                setExcelData(null);
              }}
            >
              {importloading ?
                (<div style={{ width: "90%", height: "", textAlign: "center", color: "#14d9cc" }}>
                  <Spin />
                  <div style={{ fontSize: "0.8rem", fontWeight: "500", color: "black" }}>导入中，请稍后...</div>
                  </div>)
                : (<>
                  <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
                    onClick={handlegetmb}>
                    <FileExcelOutlined /> 获取导入模板</Button>
                  <br />
                  <br />
                  <br />
                  <input
                    type='file'
                    accept='.xlsx, .xls'
                    onChange={(e) => {
                      onImportExcel(e);
                      e.target.value = null;
                    }}
                  />
                  {excelData && <div style={{ marginTop: 16 }}>已解析 {excelData.length} 条数据</div>}
                  {/* {errorRows.length > 0 && (
                    <div style={{ marginTop: 16, color: 'red' }}>
                      以下行存在手机号格式错误:
                      <ul>
                        {errorRows.map(err => (
                          <li key={err.rowNumber}>第{err.rowNumber}行手机号：{err.phone} 格式不正确</li>
                        ))}
                      </ul>
                    </div>
                  )} */}

                </>)
              }
              {/* {importError.length > 0 && (
                  <div style={{marginTop: 16, color: 'red'}}>
                    以下行社会信用代码已存在:
                    <ul>
                      {importError.map(err => (
                        <li key={err.rowNumber}>第{err.rowNumber}行社会信用代码：{err.xysbdm} 已存在</li>
                      ))}
                    </ul>
                  </div>
                )}  */}
            </Modal>
            {/* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <span style={{ fontSize: "0.8rem", fontWeight: "500" }}>高级功能</span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleEdit}>
              <SwapOutlined />同步供应商 </Button> */}
          </div>
          }

          {storage.yhlx == "租户用户" && listdata.length > 0 && listdata[0].gyswhzt !== "已维护" &&
            <div style={styleobj.linestyleflex}>
              <span style={{ fontSize: "0.8rem", fontWeight: "500", color: "#a91f24" }}>您当前尚未维护供应商档案，请尽快按照提示完成维护！</span>

            </div>
          }
          {storage.yhlx == "租户用户" && listdata.length > 0 && listdata[0].gyswhzt == "已维护" &&
            <div style={styleobj.linestyleflex}>
              <span style={{ fontSize: "0.8rem", fontWeight: "500", color: "#666666" }}>您当前已维护供应商档案，如有发生业务变更，请在【供应商变更】中发起处理！</span>

            </div>
          }

          <div style={{ width: "100%", height: "0.3vw", backgroundColor: "#F1F1F1" }}></div>
          <IconFont type="setting" style={{ position: 'absolute', right: '2vw', top: '1.2rem', fontSize: "1.5rem" }}
            onClick={() => setIsModalOpen(true)} />
          {ifshow && <Sortable tableColnum={columnarr} handleTableColomn={(data) => { setcolumnarr(data); }}
            storageName={`Pc_gys_list_${storage.userid}`} open={isModalOpen} handleOpen={(data) => { setIsModalOpen(data); }}
            initSize={initSize} handleInitSize={(data) => { setinitSize(data); storage[`Pc_gys_list__initsize_${storage.userid}`] = data; }}
          />}
          {storage.yhlx == "管理用户" && <Tabs defaultActiveKey="1" className='task-tabs' >
            {TabPaneItem("准入中", addkey_for_mxdata(listdata.filter(item => item.hzzt == "准入中")), columnarr, "1")}
            {TabPaneItem("正式", addkey_for_mxdata(listdata.filter(item => item.hzzt == "正式合作")), columnarr, "2")}
            {TabPaneItem("备选", addkey_for_mxdata(listdata.filter(item => item.hzzt == "备选")), columnarr, "3")}
            {TabPaneItem("黑名单", addkey_for_mxdata(listdata.filter(item => item.hzzt == "黑名单")), columnarr, "4")}
          </Tabs>}
          {storage.yhlx == "租户用户" && listdata.length > 0 && <ResizableTable tabledata={listdata} tablecolnum={columnarr}
            width={collapsed ? "94%" : "84%"}
            storageName={`Pc_gys_list_${storage.userid}`}
            sfdoubleclick="false" ifhiddencchangeselecttype="true"
            selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
            showCz={listdata[0].gyswhzt == "已维护" ? { showView: true } : { showEdit: true, showView: true }}
            handleEdit={(data) => handleEdit(data, "edit")}
            handleView={(data) => handleEdit(data, "view")}
            handleDelete={(data, type) => handledelete(data, type)}
            defaultPageSize={10}
            bordered
            handleselectson={(selectedRows, selectedRowKeys) => {
              setselectedRows(selectedRows)
              setselectedRowKeys(selectedRowKeys)
            }}
          />
          }
        </div>

      </div>
    </div>
  )
}


export default Gys_list


var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "8%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },


  kshcontainer: {
    width: "100%", minHeight: "40vh", position: "absolute", top: "2vh", left: "0vw", backgroundColor: "#F1F1F1",
    color: "black"
  },
}
var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },

  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96vw", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem", marginTop: "0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}